package com.example.catpict;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.example.catpict.GraphicObject;
import com.example.catpict.mainThread;
import com.example.catpict.Coordinates;

class Panel extends SurfaceView implements SurfaceHolder.Callback {
    private mainThread _thread;
    private ArrayList<GraphicObject> _graphics = new ArrayList<GraphicObject>();
    private int _x = 20;
    private int _y = 20;
    private Bitmap bg = null;

    public Panel(Context context, Bitmap background) {
        super(context);
        this.bg = background;
        getHolder().addCallback(this);
        _thread = new mainThread(getHolder(), this);
        setFocusable(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        synchronized (_thread.getSurfaceHolder()) {
            GraphicObject graphic = new GraphicObject(BitmapFactory.decodeResource(getResources(), R.drawable.icon_3));
            graphic.getCoordinates().setX((int) event.getX() - graphic.getGraphic().getWidth() / 2);
            graphic.getCoordinates().setY((int) event.getY() - graphic.getGraphic().getHeight() / 2);
            _graphics.add(graphic);
            return true;
        }
    }
     
    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawColor(Color.BLACK);
        canvas.drawBitmap(bg, 0,0, null);
        Bitmap bitmap;
        Coordinates coords;
        for (GraphicObject graphic : _graphics) {
            bitmap = graphic.getGraphic();
            coords = graphic.getCoordinates();
            canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
        }
    }

   
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub

    }

    public void surfaceCreated(SurfaceHolder holder) {
        _thread.setRunning(true);
        _thread.start();
    }

   
    public void surfaceDestroyed(SurfaceHolder holder) {
        // simply copied from sample application LunarLander:
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        _thread.setRunning(false);
        while (retry) {
            try {
                _thread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
    }
}